import { Modal } from 'ant-design-vue'

export { dataurl2file, file2dataurl } from 'dataurl-file'

const triggerFilePresets = {
  json: {
    accept: {
      'application/json': ['.json', '.json5'],
    },
    description: 'Json',
  },
  image: {
    accept: {
      'image/*': ['.png', '.gif', '.webp', '.jpeg', '.jpg'],
    },
    description: 'Image',
  },
  video: {
    accept: {
      'video/*': ['.mp4', '.webm', '.ogg'],
    },
    description: 'Video',
  },
}
export function triggerFile(
  type: keyof typeof triggerFilePresets,
  multiple?: boolean,
) {
  return new Promise<File[]>((resolve, reject) => {
    if (typeof window.showOpenFilePicker === 'function') {
      window
        .showOpenFilePicker({
          types: [triggerFilePresets[type]],
          multiple,
        })
        .then(async (fileHandles) => {
          const files: File[] = []
          for (const fileHandle of fileHandles) {
            files.push(await fileHandle.getFile())
          }
          resolve(files)
        })
        .catch(reject)
    }
    else {
      const content = '您当前浏览器不支持该特性，请升级到最新版后再试'
      Modal.confirm({
        content,
        title: '升级提示',
      })
      reject(new Error(content))
    }
  })
}

export function sizeLimit(fileSize: number, limit: number) {
  return fileSize / 1024 / 1024 < limit
}
